//
//  SCPlaceholderTextView.swift
//  GZWeibo007
//
//  Created by newuser on 15/12/27.
//  Copyright © 2015年 Apple. All rights reserved.
//

import UIKit

class SCPlaceholderTextView: UITextView {

    var placeholderText: String? {
        didSet {
            placeholderLabel.text = placeholderText
            placeholderLabel.sizeToFit()
        }
        
    
    }
    
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textDidChange", name: UITextViewTextDidChangeNotification, object: self)
        
        prepareUI()
    }
    
    
    //移除通知
    deinit {
    
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    func textDidChange() {
        //当文字发生改变隐藏
        placeholderLabel.hidden = hasText()
    
    }
    
    
    //准备UI
   func prepareUI() {
    
        addSubview(placeholderLabel)
        //添加约束
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        
        //顶部
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 8))
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 5))
    
    }

    
    private lazy var placeholderLabel: UILabel = {
    
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(18)
        label.textColor = UIColor.lightGrayColor()
        return label
    
    }()

}
